package com.chaochis.wind.util.wrapper_http;

import com.chaochis.wind.base_config.page_config.api.ApiResult;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;

/**
 * 自定义的Response包装对象
 */
public class WindResponseWrapper extends HttpServletResponseWrapper {

  private final ObjectMapper objectMapper;

  private static final String UTF8 = "UTF-8";
  private static final String CONTENT_TYPE = "application/json";

  public WindResponseWrapper(HttpServletResponse response) {
    super(response);
    this.objectMapper = new ObjectMapper();
  }

  public void setReturnResult (ApiResult<?> apiResult) throws IOException {
    this.setContentType(CONTENT_TYPE);
    this.setCharacterEncoding(UTF8);
    var printWriter = super.getWriter();
    printWriter.write(this.objectMapper.writeValueAsString(apiResult));
    printWriter.flush();
    printWriter.close();
  }

}
